package com.platform.common.config;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证码配置类
 */
@Component
@Slf4j
public class CaptchaConfig {

    @Resource
    private LineCaptcha captcha;

    /**
     * 初始化验证码格式
     */
    @Bean
    public LineCaptcha getDefaultKaptcha() {
        //定义图形验证码的长和宽
        return CaptchaUtil.createLineCaptcha(200, 100);
    }

    /**
     * 生成验证码
     */
    public void getCaptcha(HttpServletResponse response) throws IOException {
        // 重新生成验证码
        this.createCode();
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        log.debug("生成的验证码==" + captcha.getCode());
        ServletOutputStream output = null;
        try {
            output = response.getOutputStream();
            captcha.write(output);
            output.flush();
        } catch (Exception e) {
            log.error("转换异常=" + e);
        } finally {
            if (output != null) {
                output.close();
            }
        }
    }

    /**
     * 验证验证码
     */
    public boolean verify(String captchaCode) {
        return captcha.verify(captchaCode);
    }

    /**
     * 自定义验证码
     */
    private void createCode() {
        captcha.setGenerator(new RandomGenerator("0123456789", 4));
        // 重新生成code
        captcha.createCode();
    }

}
